package com.hcxdi.calanderapp.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcxdi.calanderapp.R;
import com.hcxdi.calanderapp.adapter.CalendarAdapter;
import com.hcxdi.calanderapp.bean.DayBean;
import com.hcxdi.calanderapp.utils.Lunar;
import com.hcxdi.calanderapp.utils.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CalendarView extends FrameLayout {
    RecyclerView lv;
    CalendarAdapter adapter;
    private DayBean startDate;//开始时间
    private DayBean endDate;//结束时间
    OnChooseListener onChooseListener;//选中监听
    private String startTitle="入店";
    private String endTitle="离店";
    private int showMonth=1;//显示时间范围  几个月后


    public CalendarView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public CalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CalendarView);
        startTitle=a.getString(R.styleable.CalendarView_start_title);
        endTitle=a.getString(R.styleable.CalendarView_end_title);
        showMonth=a.getInt(R.styleable.CalendarView_show_month,1);
        init(context);
    }



    /**
     * 选中的
     * @param list
     */
    public void setChoose(List<DayBean> list){
        if (null!=adapter){
            ArrayList<DayBean> data = adapter.getData();
            for (int i = 0; i <data.size(); i++) {
                for (DayBean bean:list){
                    if (data.get(i).getDate()!=null){
                        if (TimeUtils.isSameDate(data.get(i).getDate(),bean.getDate())){
                            data.get(i).setItemState(DayBean.STATE_CHOOSE);
                        }
                    }

                }
            }
            adapter.setData(data);
        }
    }

    private void init(Context context) {
        addView(LayoutInflater.from(context).inflate(R.layout.calander_view, this, false));
        lv = findViewById(R.id.lv);
        adapter = new CalendarAdapter(getContext(),startTitle,endTitle);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 7);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                if (DayBean.type_month == adapter.getData().get(i).getItemType()) {
                    return 7;
                } else {
                    return 1;
                }
            }
        });
        lv.setLayoutManager(gridLayoutManager);
        lv.setAdapter(adapter);
        adapter.getData().addAll(initCalander("", ""));
        adapter.setOnItemClickListener(new CalendarAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                onClick(adapter.getData().get(position));
            }
        });
    }


    private void onClick(DayBean dateBean) {
        if (dateBean.getItemType() == DayBean.type_month || TextUtils.isEmpty(dateBean.getDay())) {
            return;
        }
        //如果没有选中开始日期则此次操作选中开始日期
        if (startDate == null) {
            startDate = dateBean;
            dateBean.setItemState(DayBean.STATE_BEGIN_DATE);
        } else if (endDate == null) {
            //如果选中了开始日期但没有选中结束日期，本次操作选中结束日期
            //如果当前点击的结束日期跟开始日期一致 则不做操作
            if (startDate == dateBean) {

            } else if (dateBean.getDate().getTime() < startDate.getDate().getTime()) {
                //当前点选的日期小于当前选中的开始日期 则本次操作重新选中开始日期
                startDate.setItemState(DayBean.STATE_NORMAL);
                startDate = dateBean;
                startDate.setItemState(DayBean.STATE_BEGIN_DATE);
            } else {
                boolean isLock=false;//是否选择的范围中已存在锁定的位置,如果存在重置开始时间
                if (startDate != null) {
                    int start = adapter.getData().indexOf(startDate);
                    start += 1;
                    int end = adapter.getData().indexOf(dateBean);
                    for (; start < end; start++) {
                       if (adapter.getData().get(start).getItemState()==DayBean.STATE_CHOOSE){
                           isLock=true;
                           break;
                       }
                    }
                }

                if (!isLock) {
                    endDate = dateBean;
                    //选中结束日期
                    endDate.setItemState(DayBean.STATE_END_DATE);
                    setState();

                    if (onChooseListener != null) {
                        onChooseListener.onChoose(startDate, endDate);
                    }
                }else {
                  //  clearState();
                    startDate.setItemState(DayBean.STATE_NORMAL);
                    startDate = dateBean;
                    startDate.setItemState(DayBean.STATE_BEGIN_DATE);

                }
            }

        } else if (startDate != null && endDate != null) {
            //结束日期和开始日期都已选中
            clearState();

            //重新选择开始日期,结束日期清除
            startDate.setItemState(DayBean.STATE_NORMAL);
            startDate = dateBean;
            startDate.setItemState(DayBean.STATE_BEGIN_DATE);

            endDate.setItemState(DayBean.STATE_NORMAL);
            endDate = null;
        }

        adapter.notifyDataSetChanged();
    }

    //选中中间的日期
    private void setState() {
        if (endDate != null && startDate != null) {
            int start = adapter.getData().indexOf(startDate);
            start += 1;
            int end = adapter.getData().indexOf(endDate);
            for (; start < end; start++) {

                DayBean dateBean = adapter.getData().get(start);
                if (!TextUtils.isEmpty(dateBean.getDay())) {
                    dateBean.setItemState(DayBean.STATE_SELECTED);
                }
            }
        }
    }

    //取消选中状态
    private void clearState() {
        if (endDate != null && startDate != null) {
            int start = adapter.getData().indexOf(startDate);
            start += 1;
            int end = adapter.getData().indexOf(endDate);
            for (; start < end; start++) {
                DayBean dateBean = adapter.getData().get(start);
                if (dateBean.getItemState()!=DayBean.STATE_CHOOSE){
                    dateBean.setItemState(DayBean.STATE_NORMAL);
                }

            }
        }
    }



    /**
     * 生成日历数据
     */
    private List<DayBean> initCalander(String sDate, String eDate) {
        List<DayBean> dateBeans = new ArrayList<>();
        try {
            Calendar calendar = Calendar.getInstance();
            //日期格式化
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat formatYYYYMM = new SimpleDateFormat("yyyy年MM月");
            //起始日期
            Date startDate = new Date();
            calendar.setTime(startDate);
            //结束日期
            calendar.add(Calendar.MONTH, showMonth);
            Date endDate = new Date(calendar.getTimeInMillis());
            //格式化开始日期和结束日期为 yyyy-mm-dd格式
            String endDateStr = format.format(endDate);
            endDate = format.parse(endDateStr);

            String startDateStr = format.format(startDate);
            startDate = format.parse(startDateStr);

            calendar.setTime(startDate);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            Calendar monthCalendar = Calendar.getInstance();
            //按月生成日历 每行7个 最多6行 42个
            //每一行有七个日期  日 一 二 三 四 五 六 的顺序
            for (; calendar.getTimeInMillis() <= endDate.getTime(); ) {
                //月份item
                DayBean monthDateBean = new DayBean();
                monthDateBean.setDate(calendar.getTime());
                monthDateBean.setMonthStr(formatYYYYMM.format(monthDateBean.getDate()));
                monthDateBean.setItemType(DayBean.type_month);
                dateBeans.add(monthDateBean);

                //获取一个月结束的日期和开始日期
                monthCalendar.setTime(calendar.getTime());
                monthCalendar.set(Calendar.DAY_OF_MONTH, 1);
                Date startMonthDay = calendar.getTime();

                monthCalendar.add(Calendar.MONTH, 1);
                monthCalendar.add(Calendar.DAY_OF_MONTH, -1);
                Date endMonthDay = monthCalendar.getTime();
                //重置为本月开始
                monthCalendar.set(Calendar.DAY_OF_MONTH, 1);

                for (; monthCalendar.getTimeInMillis() <= endMonthDay.getTime(); ) {
                    //处理一个月开始的第一天
                    if (monthCalendar.get(Calendar.DAY_OF_MONTH) == 1) {
                        //看某个月第一天是周几
                        int weekDay = monthCalendar.get(Calendar.DAY_OF_WEEK);
                        addDatePlaceholder(dateBeans,weekDay-1,monthDateBean.getMonthStr());
                    }
                    //生成某一天日期实体 日item
                    DayBean dateBean = new DayBean();
                    dateBean.setDate(monthCalendar.getTime());
                    int year=monthCalendar.get(Calendar.YEAR);
                    int month=monthCalendar.get(Calendar.MONTH)+1;
                    int day=monthCalendar.get(Calendar.DAY_OF_MONTH);
                    Lunar lunar=new Lunar();
                    dateBean.setLunar(lunar.getLunarDate(year,month,day,true));
                    if (TimeUtils.isSameDate(monthCalendar.getTime(),Calendar.getInstance().getTime())){
                        dateBean.setDay("今天");
                    }else {
                        dateBean.setDay(day + "");
                    }
                    dateBean.setMonthStr(monthDateBean.getMonthStr());
                    dateBeans.add(dateBean);
                    //处理一个月的最后一天
                    if (monthCalendar.getTimeInMillis() == endMonthDay.getTime()) {
                        int weekDay = monthCalendar.get(Calendar.DAY_OF_WEEK);
                        addDatePlaceholder(dateBeans,7-weekDay,monthDateBean.getMonthStr());
                    }
                    //天数加1
                    monthCalendar.add(Calendar.DAY_OF_MONTH, 1);
                }
                //月份加1
                calendar.add(Calendar.MONTH, 1);
            }

        } catch (Exception ex) {

        }

        return dateBeans;
    }



    private void addDatePlaceholder(List<DayBean> dateBeans, int count, String monthStr) {
        for (int i = 0; i < count; i++) {
            DayBean dateBean = new DayBean();
            dateBean.setMonthStr(monthStr);
            dateBeans.add(dateBean);
        }
    }


    private String getWeekStr(String mWay) {
        if ("1".equals(mWay)) {
            mWay = "天";
        } else if ("2".equals(mWay)) {
            mWay = "一";
        } else if ("3".equals(mWay)) {
            mWay = "二";
        } else if ("4".equals(mWay)) {
            mWay = "三";
        } else if ("5".equals(mWay)) {
            mWay = "四";
        } else if ("6".equals(mWay)) {
            mWay = "五";
        } else if ("7".equals(mWay)) {
            mWay = "六";
        }
        return mWay;
    }

    public void setOnChooseListener(OnChooseListener onChooseListener) {
        this.onChooseListener = onChooseListener;
    }

    public interface OnChooseListener{
        void onChoose(DayBean startDate, DayBean endDate);
    }
}
